package com.cabelo.twitterMe;

import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.Twitter.User;
import winterwell.jtwitter.TwitterException;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.SharedPreferences;
import android.app.AlertDialog;
import android.content.DialogInterface;


public class twitterMe extends Activity {
	private static final String TWITTERME = "twitterMe";
    Twitter my_twiter;
    ProgressDialog dialog;
    String friendUser;
    String format;
    String userTwitter;
    String passwordTwitter;
    String returnMsg;
    boolean isTwitter;
    private static final String PACKAGE = "com.google.zxing.client.android";

    //private static final String JTWITTER_OAUTH_KEY = "this_is_populated";
    //private static final String JTWITTER_OAUTH_SECRET = "this_is_populated";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        SharedPreferences pref = getSharedPreferences(TWITTERME,0);
        userTwitter = pref.getString("login", "");
        passwordTwitter = pref.getString("password", "");
        
        final Button  capture = (Button) findViewById(R.id.button1);
        
        capture.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		my_twiter = new Twitter(userTwitter,passwordTwitter);
        		//if(my_twiter.isValidLogin())
        		//{
        			if(userTwitter != "" && passwordTwitter != ""){
        				if(my_twiter == null){
        					returnMsg = "Error in client Twitter!";
        					handler.sendEmptyMessage(0);
        					//Log.v("Twitter Status ---------------:"," Error");
        				}
        				else {
        					Log.v("Twitter Status ---------------:"," Iniciando Camera");
        					Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        					intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        					try {
        						startActivityForResult(intent, 0);

        					} catch (ActivityNotFoundException e) {
        						showDownloadDialog(twitterMe.this, "Install Barcode Scanner?", "This application requires Barcode Scanner. Would you like to install it?", "Yes", "No");
        					}


        				}
        			} else
        			{
        				returnMsg = "Login configuration not found!";
        				handler.sendEmptyMessage(0);
        			}
        		//}else{
        		//	returnMsg = "Login Invalid!";
				//    handler.sendEmptyMessage(0);
        		//}
        			
        			
        	}
        });  
        
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
      isTwitter = true;	
      if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
        	friendUser = intent.getStringExtra("SCAN_RESULT");
            format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            Log.e("MANYPLACE","BARCODE :" + friendUser);
            Log.e("MANYPLACE","BARCODE :" + format);

            if(friendUser.substring(0, 3).equalsIgnoreCase("www"))
                {
                   friendUser = "http://"+friendUser;
                   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(friendUser)));
                   isTwitter = false;
                }
            
            if(friendUser.substring(0, 4).equalsIgnoreCase("http")) 
                {
                   startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(friendUser)));
                   isTwitter = false;
                }

            if(friendUser.substring(0, 6).equalsIgnoreCase("market")) 
            {
               startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(friendUser)));
               isTwitter = false;
            }
        
            if(friendUser.substring(0, 8).equals("twitter:"))
            friendUser = friendUser.substring(8, friendUser.length());
            
        	if(friendUser.equalsIgnoreCase(userTwitter))
        	{
        		Toast.makeText(this, "This is your Twitter! Try another...", Toast.LENGTH_LONG).show();
                Log.v("Twitter Me:","This is your Twitter! Try another...");
                isTwitter = false;
        	}			  
            
            if(my_twiter == null){
                Toast.makeText(this, "Error in Twitter login!", Toast.LENGTH_LONG).show();
                Log.v("Twitter Me:"," Error in Twitter login!");	
            }
            else{
            	if(isTwitter)
            	{
            		dialog =  ProgressDialog.show(this,"Wait...","Follow "+friendUser+"...",true);
            		Thread followUser = new Thread() {
            			public void run() {
            				//Log.v("Twitter Me:"," Adicionando "+friendUser);
            				returnMsg = "Following " + friendUser;
            				friendUser = "@"+friendUser;
            				my_twiter.follow(friendUser);


            				dialog.dismiss();
            				handler.sendEmptyMessage(0);


            			}
            		};
            		followUser.start();
            	}
            }
        } 
        else if (resultCode == RESULT_CANCELED) { }
      }
    }
    
	public boolean  onCreateOptionsMenu(android.view.Menu menu){
		super.onCreateOptionsMenu(menu);
	    menu.add(0,0,0,"Config Login");
	    menu.add(0,1,0,"Create your QRCode");
	    menu.add(0,2,0,"About twitterMe");
		
		return true;
	    	
	    }

    public boolean  onMenuItemSelected(int featured, MenuItem item){
    	switch(item.getItemId()){
    	case  0:
    		
    		final Dialog dialog2 = new Dialog(twitterMe.this);	
    		dialog2.setTitle("Config Login");
    		dialog2.setContentView(R.layout.login);
    		dialog2.setCancelable(true);
    		dialog2.setCanceledOnTouchOutside(true);
    		dialog2.show();
            final Button  serverButton = (Button) dialog2.findViewById(R.id.buttonSave);
            serverButton.setOnClickListener(new SaveListener(dialog2));
            
    		final EditText tmpLogin = (EditText) dialog2.findViewById(R.id.editLogin);
    		tmpLogin.setText(userTwitter);
            
    		final EditText pwdLogin = (EditText) dialog2.findViewById(R.id.editPwd);
    		pwdLogin.setText(passwordTwitter);
            
    		
    		return true;
    	case 1:
    		Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
    		intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
    		intent.putExtra("ENCODE_DATA", userTwitter);
    		try {
    			startActivityForResult(intent, 0);
    			
    		} catch (ActivityNotFoundException e) {
    			showDownloadDialog(twitterMe.this, "Install Barcode Scanner?", "This application requires Barcode Scanner. Would you like to install it?", "Yes", "No");
    		}

    		return true;
    	case  2:	
    		 AlertDialog.Builder ab = new AlertDialog.Builder(this);
    		 ab.setMessage(Html.fromHtml("<b><font color=#0000FF> twitterMe</font></b><BR><BR>" +
    				 "<CENTER><br>Versão 1.0* Bug Report:<br>cabelo@opensuse.org<br></CENTER>"));
    		 ab.setPositiveButton("Ok", null);
    		 ab.show();
    		 return true;
    	}
    	
    	return  true;
    }		
    
	protected class SaveListener implements OnClickListener {
	   	 
        private Dialog dialog;
        public SaveListener(Dialog dialog) {
                this.dialog = dialog;
        }

        public void onClick(View v) {
          		EditText loginTmp = (EditText) dialog.findViewById(R.id.editLogin);
          		userTwitter = loginTmp.getText().toString();
          		EditText pwdTmp = (EditText) dialog.findViewById(R.id.editPwd);
          		passwordTwitter = pwdTmp.getText().toString();
                SharedPreferences pref = getSharedPreferences(TWITTERME,MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();
                editor.putString("login", userTwitter);
                editor.putString("password", passwordTwitter);
                editor.commit();
                dialog.dismiss();
                returnMsg = "Login saved!";
                handler.sendEmptyMessage(0);

        }
	}

	 public Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Toast.makeText(twitterMe.this, returnMsg, Toast.LENGTH_SHORT).show();
			}
		};	

		private static AlertDialog showDownloadDialog(final Activity activity,
				CharSequence stringTitle,
				CharSequence stringMessage,
				CharSequence stringButtonYes,
				CharSequence stringButtonNo) {
			AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
			downloadDialog.setTitle(stringTitle);
			downloadDialog.setMessage(stringMessage);
			downloadDialog.setPositiveButton(stringButtonYes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialogInterface, int i) {
					Uri uri = Uri.parse("market://search?q=pname:" + PACKAGE);
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					activity.startActivity(intent);
				}
			});
			downloadDialog.setNegativeButton(stringButtonNo, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialogInterface, int i) {}
			});
			return downloadDialog.show();
		}

		
}
